<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./index.css">
  <script src="./vue.min.js"></script>
</head>

<body>
  <div id="app">
    这是我用 express static 启动的静态服务页面
    <!-- <input type="text" v-model='name'>
    <input type="text" v-model='psw'>
    <button @click='submit'>注册</button>
    <button @click='login'>登录</button>
    <button @click='getList'>list</button> -->

    <input type="text" v-model='todo' @keydown.13='add'>
    <ul>
      <li v-for='item in list '>
        {{item.val}}
        <button @click='del(item.id)'>X</button>
      </li>
    </ul>
  </div>
</body>

</html>
<script src="./index.js"></script>
<script>
  let vm = new Vue({
    el: '#app',
    data() {
      return {
        name: "珠峰",
        psw: '',
        todo: '',
        list: []
      }
    },
    created() {
      this.getList()
    },
    methods: {
      add() {
        fetch('http://localhost:9000/add', {
          method: 'post',
          headers: {
            test_token: localStorage.getItem('token'),
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            id: Math.random(),
            val: this.todo
          })
        }).then(res => res.json()).then(data => {
          this.getList()
        })
      },
      del(id) {
        fetch('http://localhost:9000/del?id=' + id, {
          headers: {
            test_token: localStorage.getItem('token'),
            'content-type': 'application/json'
          }
        }).then(res => res.json()).then(data => {
          this.getList()
        })
      },
      getList() {
        fetch('http://localhost:9000/list', {
          headers: {
            test_token: localStorage.getItem('token'),
            'content-type': 'application/json'
          }
        }).then(res => res.json()).then(data => {
          console.log(data)
          this.list = data.data
        })
      },
      // axios
      submit() {
        fetch('http://localhost:9000/register', {
          method: 'post',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            name: this.name,
            psw: this.psw
          })
        }).then(res => res.json()).then(data => {
          console.log(data)

        })
      },
      login() {
        fetch('http://localhost:9000/login', {
          method: 'post',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            name: this.name,
            psw: this.psw
          })
        }).then(res => res.json()).then(data => {
          console.log(data)
          localStorage.setItem('token', data.token)
        })
      }
    },
  })
</script>